require 'digest/sha1'
class User < ActiveRecord::Base
  TYPES = {'Руби-гуру (хочу изучить Питон)' => 'Rubyist', 'Питон-гуру (хочу изучить Руби)' => 'Pythonist', 'Наблюдатель' => 'Guest'}

  validates_presence_of :name, :login, :email, :type, :gmt
  validates_uniqueness_of   :login, :email, :case_sensitive => false
  validates_length_of       :login,    :within => 3..20
  
  before_create :generate_secret_url
  before_create :generate_password
  
  def self.authenticate(login, password)
    u = find :first, :conditions => ['login = ?', login]
    u && u.authenticated?(password) ? u : nil
  end
  
  def authenticated?(pwd)
    self.password == pwd
  end
  
  private
  def generate_secret_url
    self.secret_url = Digest::SHA1.hexdigest("-=#{name}ЖЖ#{Time.now}=-")
  end
  
  def generate_password
    self.password = Digest::SHA1.hexdigest("!#{name}!#{type}!#{Time.now}!")[0..5]
  end
end
